package com.itheima.controller;

import com.itheima.domain.*;
import com.itheima.service.AnnouncementService;
import com.itheima.service.AnswerService;
import com.itheima.service.LikesService;
import com.itheima.service.QuestionService;
import com.itheima.until.Code;
import com.itheima.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/answers")
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @Autowired
    private LikesService likesService;
    @Autowired
    private AnnouncementService announcementService;
    @RequestMapping("/save")
    public String index(Answer answer, HttpSession session){
//        System.out.println("answer = " + answer);
//TODO 对空评论做处理
        answerService.save(answer,session);
        return "redirect:/ques/detail?qid=" + answer.getQid();
    }

    @RequestMapping("/like")
    @ResponseBody
    public String like(Integer aid, HttpSession session){
        User user = (User) session.getAttribute("user");
        int uid = user.getUid();
        Likes likes = new Likes(aid, uid);

        Likes byId = likesService.getById(likes);

        if(byId == null){
            //未点赞
            answerService.addlike(aid);
            likesService.save(likes);
        }else {
            //取消点赞
            answerService.cancellike(aid);
            likesService.delete(likes);
        }

        return "200";
    }
    @RequestMapping("/gonggao")
    @ResponseBody
    public Result gonggao(@RequestBody Announcement announcement){
//        Announcement announcement = new Announcement();
        announcement.setConcent(announcement.getConcent());
        announcement.setDate(new Date());
        announcementService.save(announcement);
        return new Result(Code.SAVE_OK,"success","发布成功");
    }


}
